package user

import (
	"gitee.com/xiaozefeng/billing-server/handler"
	"gitee.com/xiaozefeng/billing-server/handler/resp"
	"gitee.com/xiaozefeng/billing-server/model"
	"gitee.com/xiaozefeng/billing-server/pkg/auth"
	"gitee.com/xiaozefeng/billing-server/pkg/errno"
	"gitee.com/xiaozefeng/billing-server/pkg/token"
	"github.com/gin-gonic/gin"
	"github.com/lexkong/log"
)

func Login(c *gin.Context) {
	user, err := bind(c)
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	log.Infof("login user:[%s], password:[%s]", user.Name, user.Password)

	u, err := model.GetUserByName(user.Name)
	if err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "get user by name error")
		return
	}
	log.Infof("database user:%#v", u)
	if err := auth.Compare(u.Password, user.Password); err != nil {
		log.Errorf(err, "login() compare password")
		handler.SendResponse(c, errno.ErrPasswordIncorrect, nil)
		return
	}

	t, err := token.Sign(c, token.Context{Id: u.Id, Username: u.Password}, "")
	if err != nil {
		handler.SendResponse(c, errno.ErrToken, nil)
		log.Errorf(err, "login() sign token error")
		return
	}
	//set cookie
	c.SetCookie("token", t, 3600, "/", "*.*", false, true)
	handler.SendResponse(c, nil, resp.Token{Token: t})
}
